package org.jeecg.modules.xindian.reconciliation.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.DictModel;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.xindian.reconciliation.dto.rsp.DataSumStatisticsRow;
import org.jeecg.modules.xindian.reconciliation.dto.rsp.DataSumStatisticsRsp;
import org.jeecg.modules.xindian.reconciliation.dto.rsp.PlatformCodeSumStatisticsRow;
import org.jeecg.modules.xindian.reconciliation.dto.rsp.ProjectSumStatisticsRow;
import org.jeecg.modules.xindian.reconciliation.dto.*;
import org.jeecg.modules.xindian.reconciliation.entity.InsuranceStatistics;
import org.jeecg.modules.xindian.reconciliation.entity.PolicySettlementTypeStatistics;
import org.jeecg.modules.xindian.reconciliation.entity.Salesman;
import org.jeecg.modules.xindian.reconciliation.entity.SalesmanManagerRate;
import org.jeecg.modules.xindian.reconciliation.enums.RelationType;
import org.jeecg.modules.xindian.reconciliation.service.IInsuranceStatisticsService;
import org.jeecg.modules.xindian.reconciliation.service.IPolicySettlementTypeStatisticsService;
import org.jeecg.modules.xindian.reconciliation.service.ISalesmanManagerRateService;
import org.jeecg.modules.xindian.reconciliation.service.ISalesmanService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.entity.enmus.ExcelType;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.beans.PropertyEditorSupport;
import java.io.File;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: insurance_statistics
 * @Author: jeecg-boot
 * @Date: 2023-07-22
 * @Version: V1.0
 */
@Api(tags = "insurance_statistics")
@RestController
@RequestMapping("/reconciliation/insuranceStatistics")
@Slf4j
public class InsuranceStatisticsController extends JeecgController<InsuranceStatistics, IInsuranceStatisticsService> {
    @Autowired
    private IInsuranceStatisticsService insuranceStatisticsService;
    @Autowired
    private IPolicySettlementTypeStatisticsService policySettlementTypeStatisticsService;
    @Autowired
    private ISalesmanService salesmanService;
    @Autowired
    private ISalesmanManagerRateService salesmanManagerRateService;
    @Value(value = "${jeecg.path.upload}")
    private String uploadpath;

    @Autowired
    private ISysBaseAPI iSysBaseAPI;

    /**
     * 分页列表查询
     *
     * @param insuranceStatistics
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "insurance_statistics-分页列表查询")
    @ApiOperation(value = "insurance_statistics-分页列表查询", notes = "insurance_statistics-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<InsuranceStatistics>> queryPageList(InsuranceStatistics insuranceStatistics,
                                                            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                            HttpServletRequest req) {
        QueryWrapper<InsuranceStatistics> queryWrapper = QueryGenerator.initQueryWrapper(insuranceStatistics, req.getParameterMap());
        initAuthQuery(queryWrapper);
        Page<InsuranceStatistics> page = new Page<InsuranceStatistics>(pageNo, pageSize);
        IPage<InsuranceStatistics> pageList = insuranceStatisticsService.page(page, queryWrapper);
        List<InsuranceStatistics> statisticsList =  pageList.getRecords();
        //处理撞单信息
       List<String> policyNos =  statisticsList.stream().map(InsuranceStatistics::getPolicyNo).collect(Collectors.toList());
       if(CollectionUtils.isEmpty(policyNos)){
           return Result.OK(pageList);
       }
       List<PolicySettlementTypeStatistics> policySettlementTypeStatistics =   policySettlementTypeStatisticsService.lambdaQuery().in(PolicySettlementTypeStatistics::getPolicyNo,policyNos).list();
       Map<String,List<String>> types =  policySettlementTypeStatistics.stream().collect(Collectors.groupingBy(PolicySettlementTypeStatistics::getPolicyNo, Collectors.mapping(one->{
            RelationType relationType =   RelationType.valueOf(one.getType());
            switch (relationType){
                case CHANNEL:{
                    List<String> name  =new ArrayList<>();
                    if(StringUtils.hasText(one.getChannelAloneName())){
                        name.add(one.getChannelAloneName());
                    }
                    if(StringUtils.hasText(one.getChannelName())){
                        name.add(one.getChannelName());
                    }
                    return  StringUtils.collectionToCommaDelimitedString(name);
                }case SALESMAN:{
                    return one.getSalesmanName();
                } default:{
                    return "";
                }
            }
        },Collectors.toList())));
        if(!CollectionUtils.isEmpty(statisticsList)){
            statisticsList.forEach(one->{
                if(!CollectionUtils.isEmpty(types.get(one.getPolicyNo()))){
                    one.setOwners(StringUtils.collectionToCommaDelimitedString(types.get(one.getPolicyNo()).stream().filter(StringUtils::hasText).collect(Collectors.toList())));
                }
            });
        }
        return Result.OK(pageList);
    }


    /**
     * 分页列表查询
     *
     * @return
     */
    //@AutoLog(value = "insurance_statistics-分页列表查询")
    @PostMapping(value = "/loadCode")
    public Result<List<DictModel>> loadCode(@RequestBody Map<String,String> pra) {
        //判断权限
        String code = pra.get("code");
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String managerCode = "";
        if ("JYPTBM".equals(code)) {
            managerCode = sysUser.getManagePlatform();
        }
        if ("BXGS".equals(code)) {
            managerCode = sysUser.getManageInsurance();
        }
        if (!StringUtils.hasText(managerCode)) {
          return Result.ok(new ArrayList<>());
        }
        List<String> authCodes = Arrays.asList(StringUtils.commaDelimitedListToStringArray(managerCode));
        List<DictModel> dictModels = iSysBaseAPI.getDictItems(code);
        dictModels = dictModels.stream().filter(dictModel -> {
           return authCodes.contains(dictModel.getValue());
        }).collect(Collectors.toList());
        return Result.OK(dictModels);
    }

    /**
     * 分页列表查询
     *
     * @param insuranceStatistics
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "insurance_statistics-分页列表查询")
    @ApiOperation(value = "insurance_statistics-分页列表查询", notes = "insurance_statistics-分页列表查询")
    @GetMapping(value = "/qudaoshang/list")
    public Result<IPage<QuDaoShangStatisticsDto>> qudaoshangList(InsuranceStatistics insuranceStatistics,
                                                                 @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                                 @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                                 HttpServletRequest req) {
        QueryWrapper<InsuranceStatistics> queryWrapper = QueryGenerator.initQueryWrapper(insuranceStatistics, req.getParameterMap());
        initAuthQuery(queryWrapper);
        Page<InsuranceStatistics> page = new Page<InsuranceStatistics>(pageNo, pageSize);
        IPage<InsuranceStatistics> pageList = insuranceStatisticsService.page(page, queryWrapper);
        Page<QuDaoShangStatisticsDto> pageResult = new Page<>();
        pageResult.setSize(pageList.getSize());
        pageResult.setPages(pageList.getPages());
        pageResult.setTotal(pageList.getTotal());
        pageResult.setCurrent(pageList.getCurrent());
        pageResult.setRecords(pageList.getRecords().stream().map(dto -> {
            QuDaoShangStatisticsDto relDto = new QuDaoShangStatisticsDto();
            BeanUtils.copyProperties(dto, relDto);
            return relDto;
        }).collect(Collectors.toList()));
        return Result.OK(pageResult);
    }


    /**
     * 导出excel
     *
     * @param request
     * @param insuranceStatistics
     */
    //@RequiresPermissions("reconciliation:insurance_statistics:exportXls")
    @RequestMapping(value = "/qudaoshang/exportXls")
    public ModelAndView qudaoshangExportXls(HttpServletRequest request, InsuranceStatistics insuranceStatistics) {
        // Step.1 组装查询条件
        QueryWrapper<InsuranceStatistics> queryWrapper = QueryGenerator.initQueryWrapper(insuranceStatistics, request.getParameterMap());
        initAuthQuery(queryWrapper);
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        // 过滤选中数据
        String selections = request.getParameter("selections");
        if (oConvertUtils.isNotEmpty(selections)) {
            List<String> selectionList = Arrays.asList(selections.split(","));
            queryWrapper.in("id", selectionList);
        }
        // Step.2 获取导出数据
        List<QuDaoShangStatisticsDto> exportList = service.list(queryWrapper).stream().map(dto -> {
            QuDaoShangStatisticsDto relDto = new QuDaoShangStatisticsDto();
            BeanUtils.copyProperties(dto, relDto);
            return relDto;
        }).collect(Collectors.toList());

        // Step.3 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        //此处设置的filename无效 ,前端会重更新设置一下
        mv.addObject(NormalExcelConstants.FILE_NAME, "订单列表");
        mv.addObject(NormalExcelConstants.CLASS, QuDaoShangStatisticsDto.class);
        //update-begin--Author:liusq  Date:20210126 for：图片导出报错，ImageBasePath未设置--------------------
        ExportParams exportParams = new ExportParams("订单列表报表", "导出人:" + sysUser.getRealname(), "订单列表");
        mv.addObject(NormalExcelConstants.PARAMS, exportParams);
        mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
        return mv;
    }

    private void initAuthQuery(QueryWrapper<InsuranceStatistics> queryWrapper) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if(SecurityUtils.getSubject().hasRole("YWY")){
            //判断当前角色权限
           String realName = sysUser.getRealname();
          Salesman salesman =   salesmanService.lambdaQuery().eq(Salesman::getName,realName).one();
            List<String>  companys = new ArrayList<>();
            if(salesman!=null){
               List<SalesmanManagerRate>   salesmanManagerRates =   salesmanManagerRateService.queryBySalesmanId(salesman.getId());
               companys =  salesmanManagerRates.stream().map(SalesmanManagerRate::getCompany).collect(Collectors.toList());
           }
            if(CollectionUtils.isEmpty(companys)){
                queryWrapper.last("1<>1");
            }else {
                queryWrapper.in("pay_account_name", companys);
            }
        }

    }

    private void initAuthQuery(AuthQuery baseAuthQuery) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if(SecurityUtils.getSubject().hasRole("YWY")){
            //判断当前角色权限
            String realName = sysUser.getRealname();
            Salesman salesman =   salesmanService.lambdaQuery().eq(Salesman::getName,realName).one();
            List<String>  companys = new ArrayList<>();
            if(salesman!=null){
                List<SalesmanManagerRate>   salesmanManagerRates =   salesmanManagerRateService.queryBySalesmanId(salesman.getId());
                companys =  salesmanManagerRates.stream().map(SalesmanManagerRate::getCompany).collect(Collectors.toList());
            }
            if(CollectionUtils.isEmpty(companys)){
                baseAuthQuery.setNeedAll(false);
            }else {
                baseAuthQuery.setCompanys(companys);
            }
        }
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "insurance_statistics-通过id查询")
    @ApiOperation(value = "insurance_statistics-通过id查询", notes = "insurance_statistics-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<InsuranceStatistics> queryById(@RequestParam(name = "id", required = true) String id) {
        InsuranceStatistics insuranceStatistics = insuranceStatisticsService.getById(id);
        if (insuranceStatistics == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(insuranceStatistics);
    }


    /**
     * 编辑
     *
     * @param
     * @return
     */
    @AutoLog(value = "新点保单资金流水-修改渠道商")
    @ApiOperation(value = "新点保单资金流水-修改渠道商", notes = "新点保单资金流水-修改渠道商")
    @RequiresPermissions("reconciliation:insurance_statistics:channelMerchantedit")
    @RequestMapping(value = "/editChannelMerchant", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> editChannelMerchant(@RequestBody InsuranceStatistics edit) {
        InsuranceStatistics insuranceStatistics = new InsuranceStatistics();
        insuranceStatistics.setChannelProvider(edit.getChannelProvider());
        insuranceStatistics.setId(edit.getId());
        insuranceStatisticsService.updateById(insuranceStatistics);
        return Result.OK("编辑成功!");
    }

    /**
     * 导出excel
     *
     * @param request
     * @param insuranceStatistics
     */
    //@RequiresPermissions("reconciliation:insurance_statistics:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, InsuranceStatistics insuranceStatistics) {
        return processExportXls(request, insuranceStatistics, InsuranceStatistics.class, "对账统计导出");
    }

    /**
     * 导出excel
     *
     * @param request
     */
    protected ModelAndView processExportXls(HttpServletRequest request, InsuranceStatistics object, Class<InsuranceStatistics> clazz, String title) {
        // Step.1 组装查询条件
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        QueryWrapper<InsuranceStatistics> queryWrapper = QueryGenerator.initQueryWrapper(object, request.getParameterMap());
        initAuthQuery(queryWrapper);
        // 过滤选中数据
        String selections = request.getParameter("selections");
        if (oConvertUtils.isNotEmpty(selections)) {
            List<String> selectionList = Arrays.asList(selections.split(","));
            queryWrapper.in("id",selectionList);
        }
        // Step.2 获取导出数据
        List<InsuranceStatistics> exportList = service.list(queryWrapper);
        //处理撞单信息
        List<String> policyNos =  exportList.stream().map(InsuranceStatistics::getPolicyNo).collect(Collectors.toList());
        if(!CollectionUtils.isEmpty(policyNos)){
            List<PolicySettlementTypeStatistics> policySettlementTypeStatistics =   policySettlementTypeStatisticsService.lambdaQuery().in(PolicySettlementTypeStatistics::getPolicyNo,policyNos).list();
            Map<String,List<String>> types =  policySettlementTypeStatistics.stream().collect(Collectors.groupingBy(PolicySettlementTypeStatistics::getPolicyNo, Collectors.mapping(one->{
                RelationType relationType =   RelationType.valueOf(one.getType());
                switch (relationType){
                    case CHANNEL:{
                        List<String> name  =new ArrayList<>();
                        if(StringUtils.hasText(one.getChannelAloneName())){
                            name.add(one.getChannelAloneName());
                        }
                        if(StringUtils.hasText(one.getChannelName())){
                            name.add(one.getChannelName());
                        }
                        return  StringUtils.collectionToCommaDelimitedString(name);
                    }case SALESMAN:{
                        return one.getSalesmanName();
                    } default:{
                        return "";
                    }
                }
            },Collectors.toList())));
            if(!CollectionUtils.isEmpty(exportList)){
                exportList.forEach(one->{
                    if(!CollectionUtils.isEmpty(types.get(one.getPolicyNo()))){
                        one.setOwners(StringUtils.collectionToCommaDelimitedString(types.get(one.getPolicyNo()).stream().filter(StringUtils::hasText).collect(Collectors.toList())));
                    }
                });
            }
        }
        // Step.3 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        //此处设置的filename无效 ,前端会重更新设置一下
        mv.addObject(NormalExcelConstants.FILE_NAME, title);
        mv.addObject(NormalExcelConstants.CLASS, clazz);
        //update-begin--Author:liusq  Date:20210126 for：图片导出报错，ImageBasePath未设置--------------------
        ExportParams  exportParams=new ExportParams(title + "报表", "导出人:" + sysUser.getRealname(), title);
        exportParams.setType(ExcelType.HSSF);
        //update-end--Author:liusq  Date:20210126 for：图片导出报错，ImageBasePath未设置----------------------
        mv.addObject(NormalExcelConstants.PARAMS,exportParams);
        mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
        return mv;
    }

    /**
     * 渠道商订单匹配
     *
     * @return
     */
    @RequiresPermissions("reconciliation:insurance_statistics:ChannelMerchantOrderMatching")
    @RequestMapping(value = "/channelMerchantOrderMatching")
    public ModelAndView channelMerchantOrderMatching(MerchantOrderParam merchantOrderParam) {
        Assert.notNull(merchantOrderParam.getMatchType(), "匹配类型不能为空");
        Assert.notNull(merchantOrderParam.getMatchType(), "匹配类型不能为空");
        // Step.3 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        //此处设置的filename无效 ,前端会重更新设置一下
        String type = merchantOrderParam.getMatchType();
        mv.addObject(NormalExcelConstants.FILE_NAME, "渠道商订单匹配结果");
        ExportParams exportParams = new ExportParams("渠道商订单匹配结果报表", "导出人:" + sysUser.getRealname(), "渠道商订单匹配结果");
        mv.addObject(NormalExcelConstants.PARAMS, exportParams);
        Assert.notNull(merchantOrderParam.getMatchType(), "类型不能为空");
        Assert.isTrue(Arrays.asList("1", "2").contains(merchantOrderParam.getMatchType()), "上传类型不正确");
        Assert.notNull(merchantOrderParam.getWenjian(), "上传那文件不能为空");
        // 获取上传文件对象
        File file = new File(uploadpath + File.separator + File.separator + File.separator + merchantOrderParam.getWenjian());
        ImportParams params = new ImportParams();
        params.setTitleRows(0);
        params.setHeadRows(0);
        switch (type) {
            case "1": {
                List<MatchBaoDanHao> list = null;
                try {
                    list = ExcelImportUtil.importExcel(file, MatchBaoDanHao.class, params);
                } catch (Exception e) {
                    log.error("导入失败",e);
                    throw new RuntimeException(e);
                }
                checkMatchBaoDanHao(list);
                insuranceStatisticsService.matchBaoHan(list);
                mv.addObject(NormalExcelConstants.CLASS, MatchBaoDanHao.class);
                mv.addObject(NormalExcelConstants.DATA_LIST, list);
            }
            break;
            case "2": {
                List<MatchProjectName> list = null;
                try {
                    list = ExcelImportUtil.importExcel(file, MatchProjectName.class, params);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
                checkMatchProjectName(list);
                insuranceStatisticsService.matchProject(list);
                mv.addObject(NormalExcelConstants.CLASS, MatchProjectName.class);
                mv.addObject(NormalExcelConstants.DATA_LIST, list);
            }
            break;
        }
        return mv;
    }

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        // Date 类型转换
        binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) {
                setValue(DateUtil.parse(text));
            }
        });
    }

    private void checkMatchProjectName(List<MatchProjectName> list) {
        Assert.notEmpty(list, "上传匹配信息不能为空");
        int i = 1;
        list.forEach(row -> {
            Assert.notNull(row.getProjectName(), "第{}行保单号不能为空", i);
            Assert.notNull(row.getMerchantName(), "第{}行渠道商名称不能为空", i);
            Assert.notNull(row.getPolicyHolderName(), "第{}行投保人名称不能为空", i);
        });
    }

    private void checkMatchBaoDanHao(List<MatchBaoDanHao> list) {
        Assert.notEmpty(list, "上传匹配信息不能为空");
        int i = 1;
        list.forEach(row -> {
            Assert.notNull(row.getPolicyNo(), "第{}行保单号不能为空", i);
            Assert.notNull(row.getMerchantName(), "第{}行渠道商名称不能为空", i);
        });
    }


    /**
     * 数据统计
     *
     * @return
     */
    @ApiOperation(value = "查询数据统计", notes = "查询数据统计")
    @PostMapping(value = "/queryTotalDataStatistics")
    public Result<DataSumStatisticsRsp> queryTotalDataStatistics(@RequestBody StatisticsQuery dataStatistics) {
        processDate(dataStatistics);
        initAuthQuery(dataStatistics);
        DataSumStatisticsRsp dataSumStatisticsRsp = insuranceStatisticsService.dataSumStatistics(dataStatistics);
        return Result.OK(dataSumStatisticsRsp);
    }

    private void processDate(StatisticsQuery dataStatistics) {
        if (dataStatistics.getPayBegin() != null) {
            dataStatistics.setPayBegin(DateUtil.beginOfDay(dataStatistics.getPayBegin()));
        }
        if (dataStatistics.getPayEnd() != null) {
            dataStatistics.setPayEnd(DateUtil.endOfDay(dataStatistics.getPayEnd()));
        }
    }

    /**
     * 数据统计
     *
     * @return
     */
    @ApiOperation(value = "查询数据统计", notes = "查询数据统计")
    @GetMapping(value = "/queryDataStatistics")
    public Result<IPage<DataSumStatisticsRow>> queryDataStatistics(StatisticsQuery dataStatistics,
                                                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        processDate(dataStatistics);
        initAuthQuery(dataStatistics);
        Page page = new Page(pageNo, pageSize);
        IPage<DataSumStatisticsRow> dataStatisticsVOIPage = insuranceStatisticsService.queryDataSumStatisticsRow(page, dataStatistics);
        return Result.OK(dataStatisticsVOIPage);
    }

    /**
     * 数据统计导出excel
     */
    @RequestMapping(value = "/exportDataStatistics")
    public ModelAndView exportDataStatistics(StatisticsQuery dataStatistics) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        processDate(dataStatistics);
        initAuthQuery(dataStatistics);
        List<DataSumStatisticsRow> dataSumStatisticsRsp = insuranceStatisticsService.queryDataSumStatisticsRowAll(dataStatistics);
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, "数据统计列表");
        mv.addObject(NormalExcelConstants.CLASS, DataSumStatisticsRow.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("数据统计", "导出人:" + sysUser.getRealname(), "数据统计"));
        mv.addObject(NormalExcelConstants.DATA_LIST, dataSumStatisticsRsp);
        return mv;
    }

    /**
     * 平台统计
     *
     * @return
     */
    @ApiOperation(value = "根据projectId查询保险统计", notes = "根据projectId查询保险统计")
    @GetMapping(value = "/queryPlatformCodeStatistics")
    public Result<IPage<PlatformCodeSumStatisticsRow>> queryPlatformCodeStatistics(StatisticsQuery statisticsQuery,
                                                                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        processDate(statisticsQuery);
        initAuthQuery(statisticsQuery);
        Page page = new Page(pageNo, pageSize);
        IPage<PlatformCodeSumStatisticsRow> dataStatisticsVOIPage = insuranceStatisticsService.queryInsuranceSumStatisticsRow(page, statisticsQuery);
        return Result.OK(dataStatisticsVOIPage);
    }


    /**
     * 数据统计列表导出
     */
    @RequestMapping(value = "/exportPlatformCodeStatistics")
    public ModelAndView exportPlatformCodeStatistics(StatisticsQuery statisticsQuery) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        processDate(statisticsQuery);
        initAuthQuery(statisticsQuery);
        List<PlatformCodeSumStatisticsRow> dataSumStatisticsRsp = insuranceStatisticsService.queryInsuranceSumStatisticsRowAll(statisticsQuery);
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, "数据统计列表");
        mv.addObject(NormalExcelConstants.CLASS, PlatformCodeSumStatisticsRow.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("数据统计列表", "导出人:" + sysUser.getRealname(), "保险统计"));
        mv.addObject(NormalExcelConstants.DATA_LIST, dataSumStatisticsRsp);
        return mv;
    }

    /**
     * 地区统计
     *
     * @return
     */
    @ApiOperation(value = "根据areaId查询地区统计", notes = "根据areaId查询地区统计")
    @GetMapping(value = "/queryRegionalStatistics")
    public Result<IPage<ProjectSumStatisticsRow>> queryRegionalStatistics(StatisticsQuery dataStatistics,
                                                                          @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                                          @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        processDate(dataStatistics);
        initAuthQuery(dataStatistics);
        IPage<ProjectSumStatisticsRow> regionalStatisticsVOIPage = insuranceStatisticsService.queryProjectSumStatisticsRow(new Page(pageNo, pageSize), dataStatistics);
        regionalStatisticsVOIPage.getRecords().stream().forEach(rd -> {
            rd.setAreaId(dataStatistics.getAreaId());
        });
        return Result.OK(regionalStatisticsVOIPage);
    }

    /**
     * 地区统计导出excel
     *
     * @param dataStatistics
     */
    @RequestMapping(value = "/exportRegionalStatistics")
    public ModelAndView exportRegionalStatistics(StatisticsQuery dataStatistics) {
        processDate(dataStatistics);
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        List<ProjectSumStatisticsRow> regionalStatisticsVOS = insuranceStatisticsService.queryProjectSumStatisticsRowAll(dataStatistics);
        // Step.4 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, "地区统计列表");
        mv.addObject(NormalExcelConstants.CLASS, ProjectSumStatisticsRow.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("地区统计数据", "导出人:" + sysUser.getRealname(), "地区统计"));
        mv.addObject(NormalExcelConstants.DATA_LIST, regionalStatisticsVOS);
        return mv;
    }
}
